# -*- coding: UTF-8 -*-
"""
HaaS506 DTU - Time Sync Module (Simplified)
Function: HTTP time sync using driver.RTC
Version: v1.0.6
"""

import service_storage
import utime as time
import usocket as socket
import ujson
import config
from driver import RTC
import mod_network

# 配置
CONFIG = {"server": "dtu.coldwang.com/api/time", "timeout": 10}
# 最早时间2025-01-01
MIN_TIMESTAMP = 1735660800

# 模块状态
module_status = "STOPPED"
last_sync_time = 0

# ----------------------------
# 工具函数
# ----------------------------


def get_current_beijing_timestamp():
    """当前北京时间戳"""
    return int(time.time())  # 不加 +8，小心！


def get_current_beijing_time():
    """获取当前北京时间字符串（HaaS 已自动 +8）"""
    try:
        tm = time.localtime()  # 不加 +8
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*tm[:6])
    except:
        return "Unknown"


def get_current_time_utc():
    """仅调试用：UTC 时间字符串"""
    try:
        tm = time.gmtime()  # gmtime 是 UTC
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*tm[:6])
    except:
        return "Unknown"


# ----------------------------
# 模块功能函数
# ----------------------------


def init():
    """初始化模块"""
    global module_status
    try:
        config_data = config.get_config()
        time_config = config_data.get("servers", {})
        server_url = time_config.get("time_server")
        if server_url:
            # 移除 http:// 或 https:// 前缀
            if server_url.startswith("http://"):
                server_url = server_url[7:]
            elif server_url.startswith("https://"):
                server_url = server_url[8:]
            CONFIG["server"] = server_url
        timeout = time_config.get("time_timeout", 10)
        CONFIG["timeout"] = timeout
        module_status = "RUNNING"
        print("[TIME] Time sync module initialized")
        sync_time()
        print(
            "[TIME] ===> get_current_beijing_time: {}".format(
                get_current_beijing_time()
            )
        )
        return True
    except Exception as e:
        print("[TIME] Time sync init error:", e)
        module_status = "ERROR"
        print(
            "[TIME] ===> get_current_beijing_time: {}".format(
                get_current_beijing_time()
            )
        )
        return False


def start():
    """启动模块（无需重复初始化）"""
    if module_status == "RUNNING":
        print("[TIME] Time sync module started")
        return True
    print("[TIME] Time sync module not initialized")
    return False


def cleanup():
    """关闭模块"""
    global module_status
    module_status = "STOPPED"


def is_time_synced():
    """判断时间是否已经同步成功"""
    try:
        if last_sync_time == 0:
            return False
        if time.time() < MIN_TIMESTAMP:  # 2025-01-01
            return False
        return True
    except:
        return False


def sync_time():

    if not mod_network.getNetFlag():
        # 网络未连接，尝试从缓存恢复时间
        print("[TIME] sync_time Failed, network not connected")
        reset_from_cache_time()
        return False

    """从服务器同步 UTC 时间并设置 RTC"""
    global last_sync_time

    try:
        host = CONFIG["server"].split("/", 1)[0]
        path = (
            "/" + CONFIG["server"].split("/", 1)[1]
            if "/" in CONFIG["server"]
            else "/time"
        )
        timeout = CONFIG.get("timeout", 10)

        print("[TIME] server: {}{}".format(host, path))

        addr = socket.getaddrinfo(host, 80)[0][-1]
        sock = socket.socket()
        sock.settimeout(timeout)
        sock.connect(addr)

        # 构建请求，包含当前版本信息和设备编号
        request_data = {
            "action": "time_sync",
            "current_version": config.get_config("system.version"),
            "device_sn": config.get_config("device.device_sn"),
            "device_type": "haas506_dtu",
        }
        print("[TIME] request_data: {}".format(request_data))
        # request = "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n".format(
        #     path, host
        # )
        request = "POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{}".format(
            path, host, len(ujson.dumps(request_data)), ujson.dumps(request_data)
        )

        sock.send(request.encode())

        response = sock.read()
        sock.close()

        body = response.decode().split("\r\n\r\n", 1)[-1]
        print("[TIME] Raw body: {}".format(body))
        data = ujson.loads(body)

        timestamp = int(data.get("timestamp", 0))

        if timestamp > 1e12:
            timestamp = timestamp // 1000

        if timestamp <= 0:
            print("[TIME] error timestamp: {}".format(timestamp))
            return False

        if timestamp < MIN_TIMESTAMP:
            print("[TIME] error timestamp, too early: {}".format(timestamp))
            return False

        # 设置 RTC 为 UTC 时间
        reset_system_time(timestamp)

        print("[TIME] reset_system_time timestamp: {}".format(timestamp))
        config.g_time_synced = True
        return True

    except Exception as e:
        print("[TIME] sync time error: {}".format(e))

        # 同步失败，从缓存恢复时间
        # 由于RTC设置为UTC时间，time.time()现在应该返回UTC时间戳

        # 从缓存恢复时间
        reset_from_cache_time()

        return False


def reset_from_cache_time():
    current_time = time.time()
    if current_time < MIN_TIMESTAMP:
        print("[TIME] sync time failed, current time: {} (UTC)".format(current_time))
        cache_time = service_storage.runtime_storage.read_last_timestamp()
        if cache_time > MIN_TIMESTAMP:
            print(
                "[TIME] sync time failed, read_last_timestamp: {} (UTC)".format(
                    cache_time
                )
            )
            # cache_time是UTC时间戳，可以直接传给reset_system_time
            reset_system_time(cache_time + 60)


# reset system time to 2025-01-01 00:00:00
def reset_system_time(timestamp):
    # 使用 gmtime 确保设置的是 UTC 时间，避免时区转换
    # HaaS506 的 RTC 应该设置为 UTC 时间，系统会自动处理时区显示
    tm = time.gmtime(timestamp)
    rtc = RTC()
    rtc.open()
    rtc.setTime(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5])
    print("[TIME] reset system time to {} (UTC)".format(tm))

    # 更新最后同步时间戳
    global last_sync_time
    last_sync_time = timestamp


# ----------------------------
# 信息接口
# ----------------------------


def get_module_status():
    time_since_sync = int(time.time() - last_sync_time) if last_sync_time > 0 else -1
    return {
        "status": module_status,
        "current_time_utc": get_current_time_utc(),
        "current_time_beijing": get_current_beijing_time(),
        "last_sync_ago": (
            "{}s".format(time_since_sync) if time_since_sync >= 0 else "Never"
        ),
    }


def get_module_info():
    return {
        "name": "Time Sync Module (Simplified)",
        "version": "v1.0.6",
        "description": "HTTP UTC time synchronization for RTC",
        "status": module_status,
        "server": CONFIG["server"],
    }
